/**
 * Javascript file for sources needed at playerinformation.php
 */

function update_playerinformation_notice() {
	var xhrArgs = {
	        url: "ajax/ajax_notices.php?type=update",
	        form: dojo.byId("notice_edit"),
	        handleAs: "json",
	        load: function(jsonData) {
	        	showMessages(jsonData);
	        },
	        error: function(error) {
				console.log("Error:");
				console.log(error);
	        }
	}	
	dojo.xhrPost(xhrArgs);	
	return false; // to avoid form submit
}

function galaxytool_moon_report_formatter(val, rowIdx, cell) {
	return galaxytool_report_formatter(val, rowIdx, cell, moonstore, moongrid);
}
function galaxytool_planet_report_formatter(val, rowIdx, cell) {
	return galaxytool_report_formatter(val, rowIdx, cell, planetstore, planetgrid);
}

//formatter for column 0
function galaxytool_report_formatter(val, rowIdx, cell, store, grid) {
	var key = store.getValue(grid.getItem(rowIdx), "key");
	
	if (key == "id" || key == "h1" || key == "h3" || key == "h4") {
		cell.customClasses.push("public");
		if (key != "msg_id") {
			val = '<div style="height:16px;">'+val+'</div>';
		}
	}
	if (key == "coordinates") {
		val = '<div style="height:16px;">'+val+'</div>';
	}
	
	if (key == "res_sum" || key == "def_sum") {
		val = "&sum; " + val;
		cell.customClasses.push("sum_row");
	}

	return val;
}

function galaxytool_moon_report_formatter2(val, rowIdx, cell) {
	return galaxytool_report_formatter2(val, rowIdx, cell, moonstore, moongrid, true);
}
function galaxytool_planet_report_formatter2(val, rowIdx, cell) {
	return galaxytool_report_formatter2(val, rowIdx, cell, planetstore, planetgrid, false);
}

function galaxytool_report_formatter2(val, rowIdx, cell, store, grid, galaxytool_is_moon) {
	cell.customClasses.push("centered_text");
	
	if (rowIdx == 0) {
		// val = coordinates
		if (galaxytool_is_moon) {
			return '<img onclick="show_report(\''+val+'\',true)" src="../images/magnifier2.png" style="cursor: pointer;">';			
		}
		return '<img onclick="show_report(\''+val+'\',false)" src="../images/magnifier2.png" style="cursor: pointer;">';
	}
	
	var key = store.getValue(grid.getItem(rowIdx), "key");
	if (key == "res_sum" || key == "fleet_sum" || key == "def_sum") {
		cell.customClasses.push("sum_row");
	} else if ((key == "metal" || key == "crystal" || key == "deuterium") && val > 0) {
		// use different colors for resources depending on storage capacity
		var size = 0;
		var buildings = store.getValue(grid.getItem(10), cell.field);
		if (store.getValue(grid.getItem(10), "key") != "h4") console.log("new lines added - adjust playerinformation.js!");
		
		if (buildings == "ok") {
			if (galaxytool_is_moon == false) {
				switch(key) {
				case "metal": size = store.getValue(grid.getItem(13), cell.field); break;
				case "crystal": size = store.getValue(grid.getItem(14), cell.field); break;
				case "deuterium": size = store.getValue(grid.getItem(15), cell.field); break;
				}
				if (store.getValue(grid.getItem(13), "key") != "mesp") console.log("new lines added - adjust playerinformation.js!");
			} else {
				// use moon index
				switch(key) {
				case "metal": size = store.getValue(grid.getItem(20), cell.field); break;
				case "crystal": size = store.getValue(grid.getItem(21), cell.field); break;
				case "deuterium": size = store.getValue(grid.getItem(22), cell.field); break;
				}
				if (store.getValue(grid.getItem(20), "key") != "mesp") console.log("new lines added - adjust playerinformation.js!");
			}
		}
		
		if (buildings == "ok" || galaxytool_is_moon == true) {
			var capacity = galaxytool.report_display.get_storage_capacity(parseInt(size));
			var stored = parseInt(val);
			
			if (capacity <= stored) {
				cell.customClasses.push("traffic_light_red");
				
			} else if (capacity * 0.9 <=  stored) {
				cell.customClasses.push("traffic_light_yellow");
			}
		}
	} else if (key == "h1" || key == "h3" || key == "h4") {
		return "";
	}
	
	if (!isNaN(parseFloat(val)) && isFinite(val)) {
		// value is numeric
		return NumberFormat(val);
	}

	return val;
}

function create_moon_table() {
    if ("object" != typeof(player_moon_data["items"])) return;
	moonstore = new dojo.data.ItemFileReadStore({data: player_moon_data});
    moongrid.setStore(moonstore);
	
	var layout = get_layout(galaxytool_moon_report_formatter, galaxytool_moon_report_formatter2, player_moon_data["items"][0]);
	// set the new layout structure:
	moongrid.set('structure',layout);
	
}

function create_planet_table() {
    if ("object" != typeof(player_planet_data["items"])) return;
    planetstore = new dojo.data.ItemFileReadStore({data: player_planet_data});
    planetgrid.setStore(planetstore);
	
	var layout = get_layout(galaxytool_planet_report_formatter, galaxytool_planet_report_formatter2, player_planet_data["items"][0]);
	// set the new layout structure:
	planetgrid.set('structure',layout);
}

function get_layout(formatter1, formatter2, first_row) {
	var columns = 0;
	var column_name = "";
	for (i in first_row) {
		if (i.indexOf("c") == 0) {
			columns++;
		}
	}
		
	var fixlayout = {
			noscroll: true,
			cells: [{
				field: 'c0',
				name: 'c0',
				width: '150px',
				formatter: formatter1  
			}]
		};	

	var mainlayout = new Array(columns);
	for (var i=1; i<columns; i++) {
		mainlayout[i-1] = {
			field: 'c'+i,
			name: '',
			width: '85px',
			formatter: formatter2
		};
	}
	
	return [fixlayout, mainlayout];  
}

function delete_player(id) {

	if (confirm(galaxytool_admin_safety_text) != true) {
		return;
	}
	
	var player_id  = parseInt(id);
	if (player_id < 1) return;
	
	var xhrArgs = {
	        url: "ajax/ajax_stats.php?type=player_delete&player_id="+player_id,
	        handleAs: "text",
	        load: function(text) {
	        	if (text == "true") {
	        		window.location.href="index.php";
	        	}
	        },
	        error: function(error) {
				console.log("Error:");
				console.log(error);
	        }
	}	
	dojo.xhrPost(xhrArgs);
}

function galaxytool_playerstatus(id, NewStatus) {
	var player_id  = parseInt(id);
	if (player_id < 1) return;
	
	var xhrArgs = {
			url: "ajax/ajax_stats.php?type=change_player&player_id="+player_id+"&new_status="+NewStatus,
			handleAs: "text",
			load: function(text) {
				if (text == "true") {
					// change color
					dojo.byId("pn_"+player_id).setAttribute("class", NewStatus);
				}
			},
			error: function(error) {
				console.log("Error:");
				console.log(error);
			}
	}	
	dojo.xhrPost(xhrArgs);
}


function galaxytool_playerinformation_init() {
	
	dojo.connect(dijit.byId("reporttooltip"), "onMouseLeave", galaxytool.report_display.CloseReportTooltip );
	dojo.connect(dijit.byId("reporttooltip"), "onMouseOver", galaxytool.report_display.ReportTooltipMouseOver );
	
	// select user defined tab
	var choosen_tab = window.location.hash;
	if (choosen_tab != "") {
		try {
			choosen_tab = choosen_tab.replace(/#select_/, "");
			dijit.byId("tabcontainer").selectChild(dijit.byId(choosen_tab));
		} catch (ignore) {
			// select default tab in case of wrong user input
		}
	}

	dojo.subscribe("tabcontainer-selectChild", function(child) {
		window.location.hash = "#select_" + child.get("id");
		// disable message area
		dojo.byId("messageArea").style.display  = "none";
		
		if (child.get("id") == "tab5" || child.get("id") == "tab6") {
			// hide table header for planet and moon into
			dojo.query(".dojoxGridMasterHeader").style("display", "none");			
		}
	});
	
	if (dojo.byId("tab5") != null) create_planet_table();
	if (dojo.byId("tab6") != null) create_moon_table();
	if (choosen_tab == "tab5" || choosen_tab == "tab6") {
		// initially hide table header if grid is loaded for planet or moon tab
		// TODO: check why it does not work for direct loading of tab5 but works fine for tab6
		dojo.query(".dojoxGridMasterHeader").style("display", "none");		
	}
	

}

dojo.ready(galaxytool_playerinformation_init);
